package com.hafu.swing;

import com.hafu.model.Course;
import com.hafu.service.CourseService;
import com.hafu.service.TeacherService;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

// 课程管理面板
public class CourseManagePanel extends JPanel {
    private CourseService courseService;
    private JTable courseTable;
    private DefaultTableModel tableModel;
    private TeacherService teacherService;

    public CourseManagePanel(JPanel parentPanel, CourseService courseService) {
        this.courseService = courseService;
        this.teacherService = new TeacherService();
        setLayout(new BorderLayout());

        // 顶部工具栏
        JPanel toolbarPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        JButton addButton = new JButton("添加课程");
        JButton editButton = new JButton("编辑课程");
        JButton deleteButton = new JButton("删除课程");
        JButton auditButton = new JButton("审核课程");
        JButton refreshButton = new JButton("刷新");
        JTextField searchField = new JTextField(15);
        JButton searchButton = new JButton("搜索");

        toolbarPanel.add(addButton);
        toolbarPanel.add(editButton);
        toolbarPanel.add(deleteButton);
        toolbarPanel.add(auditButton);
        toolbarPanel.add(new JSeparator(SwingConstants.VERTICAL));
        toolbarPanel.add(new JLabel("课程ID/名称:"));
        toolbarPanel.add(searchField);
        toolbarPanel.add(searchButton);
        toolbarPanel.add(refreshButton);

        // 表格数据
        String[] columnNames = {"课程ID", "课程名称", "授课教师", "学分", "课时", "状态", "创建时间", "操作"};
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return column == 7; // 只允许编辑最后一列(操作)
            }
        };
        courseTable = new JTable(tableModel);
        courseTable.setRowHeight(30);
        courseTable.getColumnModel().getColumn(0).setPreferredWidth(80);
        courseTable.getColumnModel().getColumn(1).setPreferredWidth(150);
        courseTable.getColumnModel().getColumn(2).setPreferredWidth(100);
        courseTable.getColumnModel().getColumn(3).setPreferredWidth(50);
        courseTable.getColumnModel().getColumn(4).setPreferredWidth(50);
        courseTable.getColumnModel().getColumn(5).setPreferredWidth(80);
        courseTable.getColumnModel().getColumn(6).setPreferredWidth(120);
        courseTable.getColumnModel().getColumn(7).setPreferredWidth(100);

        JScrollPane scrollPane = new JScrollPane(courseTable);

        // 加载课程数据
        loadCourseData();

        // 按钮事件
        addButton.addActionListener(e -> new AddCourseDialog(this, courseService).setVisible(true));

        editButton.addActionListener(e -> {
            int selectedRow = courseTable.getSelectedRow();
            if (selectedRow >= 0) {
                String courseId = (String) tableModel.getValueAt(selectedRow, 0);
                JFrame parentFrame = (JFrame) SwingUtilities.getWindowAncestor(this);
                new EditCourseDialog(parentFrame, courseService, courseId).setVisible(true);
            } else {
                JOptionPane.showMessageDialog(this, "请先选择要编辑的课程", "提示", JOptionPane.WARNING_MESSAGE);
            }
        });

        deleteButton.addActionListener(e -> {
            int selectedRow = courseTable.getSelectedRow();
            if (selectedRow >= 0) {
                String courseId = (String) tableModel.getValueAt(selectedRow, 0);
                int confirm = JOptionPane.showConfirmDialog(this,
                        "确定要删除课程ID为" + courseId + "的课程吗?", "确认删除", JOptionPane.YES_NO_OPTION);
                if (confirm == JOptionPane.YES_OPTION) {
                    if (courseService.deleteCourse(courseId)) {
                        JOptionPane.showMessageDialog(this, "删除成功", "成功", JOptionPane.INFORMATION_MESSAGE);
                        loadCourseData();
                    } else {
                        JOptionPane.showMessageDialog(this, "删除失败", "失败", JOptionPane.ERROR_MESSAGE);
                    }
                }
            } else {
                JOptionPane.showMessageDialog(this, "请先选择要删除的课程", "提示", JOptionPane.WARNING_MESSAGE);
            }
        });

        auditButton.addActionListener(e -> {
            int selectedRow = courseTable.getSelectedRow();
            if (selectedRow >= 0) {
                String courseId = (String) tableModel.getValueAt(selectedRow, 0);
                String status = (String) tableModel.getValueAt(selectedRow, 5);
                if ("待审核".equals(status)) {
                    JFrame parentFrame = (JFrame) SwingUtilities.getWindowAncestor(this);
                    new AuditCourseDialog(parentFrame, courseService, courseId).setVisible(true);
                } else {
                    JOptionPane.showMessageDialog(this, "该课程不需要审核", "提示", JOptionPane.INFORMATION_MESSAGE);
                }
            } else {
                JOptionPane.showMessageDialog(this, "请先选择要审核的课程", "提示", JOptionPane.WARNING_MESSAGE);
            }
        });

        searchButton.addActionListener(e -> {
            String keyword = searchField.getText().trim();
            if (!keyword.isEmpty()) {
                searchCourses(keyword);
            } else {
                loadCourseData();
            }
        });

        refreshButton.addActionListener(e -> loadCourseData());

        add(toolbarPanel, BorderLayout.NORTH);
        add(scrollPane, BorderLayout.CENTER);
    }

    // 加载课程数据
    private void loadCourseData() {
        tableModel.setRowCount(0);
        List<Course> courses = courseService.getAllCourses();
        for (Course course : courses) {
            Object[] rowData = {
                    course.getCourseId(),
                    course.getCourseName(),
                    getTeacherNameFromService(course.getTeacherId()),
                    course.getCredits(),
                    course.getHours(),
                    course.getStatus(),
                    course.getCreateTime(),
                    "查看详情"
            };
            tableModel.addRow(rowData);
        }
    }

    // 搜索课程
    private void searchCourses(String keyword) {
        tableModel.setRowCount(0);
        List<Course> courses = courseService.searchCourses(keyword);
        for (Course course : courses) {
            Object[] rowData = {
                    course.getCourseId(),
                    course.getCourseName(),
                    getTeacherNameFromService(course.getTeacherId()),
                    course.getCredits(),
                    course.getHours(),
                    course.getStatus(),
                    course.getCreateTime(),
                    "查看详情"
            };
            tableModel.addRow(rowData);
        }
    }

    // 从服务获取教师名称
    private String getTeacherNameFromService(String teacherId) {
        if (teacherId == null || teacherId.trim().isEmpty()) {
            return "未指定教师";
        }
        try {
            return teacherService.getTeacherName(teacherId);
        } catch (Exception e) {
            e.printStackTrace();
            return "教师加载失败";
        }
    }

    // 刷新数据
    public void refreshData() {
        loadCourseData();
    }
}